# -*- coding: utf-8 -*-
# Copyright 2011-2012 MagiCycles.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import logging

from google.appengine.ext import db

class OAuthUploadSignatures(db.Model):
    signature = db.StringProperty()
    uid = db.StringProperty()
    count = db.IntegerProperty(default=0)

    key_template = "oauth/uploadsign/%(signature)s"

    @classmethod
    def generate_key_name(cls, **kw):
        try:
            return cls.key_template % kw
        except KeyError:
            logging.warn('generate key_name failed: %s <- %s',
                cls.key_template, kw)

    @classmethod
    def check_sign_exist(cls, signature):
        key_name = cls.generate_key_name(signature=signature)
        return cls.get_by_key_name(key_name)

    @classmethod
    def insert_sign(cls, uid, signature):
        key_name = cls.generate_key_name(signature=signature)
        upload_signature = cls(key_name=key_name, uid=uid, signature=signature)
        upload_signature.put()
        return upload_signature
